$(function() {
    // 倒计时
    var countdowna = 6;
    var isClicked = false;
    var originalBgColor = $("#submit").css("background-color");
    $('#createConversationForm').submit(function(event) {
        event.preventDefault();
        if (!isClicked) {
            isClicked = true;
            $("#submit").css("background-color", "gray");
            $("#submit").prop("disabled", true);
            // 开启定时器
            var countdownInterval = setInterval(function() {
                countdowna = countdowna*1-1; // 每秒减少1秒
                $("#submit").text(countdowna + "秒");
                if (countdowna == 0) {
                    // 清除定时器
                    clearInterval(countdownInterval);
                    // 重新初始化倒计时
                    countdowna = 6;
                    // 恢复默认效果
                    $("#submit").css("background-color", originalBgColor);
                    $("#submit").text("提问");
                    $("#submit").prop("disabled", false);
                    isClicked = false;
                }
            }, 2000);
        }

        var form = $(this);
        var prompt = form.find('#prompt').val();
        // console.log(prompt);
        $.ajax({
            type: 'POST',
            url: 'conversation.php',
            data: {
                prompt: prompt
            },
            success: function(content) {
                // var newObj = JSON.parse(response);
                var answer = "<div class='move-css' style='color:#29b9b9fa;padding-bottom: 6px;font-weight:bold;'><span style='width:20px;'>我：</span>"+prompt+"</div>";
                //var text = "<div><span style='width:20px;'>AI：</span>"+content+"</div><hr style='margin-top:20px;' />";
                $('#conversationContainer').append(answer);
                if(hasSpecialChar(content)) {
                    $contentAppend = "<pre>"+content+"</pre> <hr style='margin-top:20px;' />";
                }else{
                    $contentAppend = content+"<hr style='margin-top:20px;'/>";
                }

                $('#conversationContainer').append($contentAppend);
                $("#hrtag").show();
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
    });

    function hasSpecialChar(str) {
        var pattern = /[~!@#$%^&*_+|\\[\](){};:'",.<>?\/]/;
        return pattern.test(str);
    }


});